#include<iostream>
#include <pthread.h>
#include<vector>
#include"Thread.hpp"
#define NUM 4
using namespace ThreadModule;

int ticketnum = 10000; // 共享资源
//全局锁
//pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

//局部锁传参构造，一个是线程名，另一个是共同的锁
class ThreadData
{
public:
    std::string name;
    pthread_mutex_t *mutex_ptr;

};

void Ticket(ThreadData &td)
{
    while (true)
    {
        pthread_mutex_lock(td.mutex_ptr);
        if (ticketnum > 0)
        {
            usleep(1000);
            // 1. 抢票
            printf("get a new ticket, id: %d,who get a ticket: %s\n", ticketnum--,td.name.c_str());

            pthread_mutex_unlock(td.mutex_ptr);

            // 2. 入库模拟
            usleep(50);
        }
        else
        {
            pthread_mutex_unlock(td.mutex_ptr);
            break;
        }
    }
}

//局部锁
int main()
{
    //创建并初始化局部锁
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex,nullptr);
    // 1. 构建线程对象
    std::vector<Thread<ThreadData>> threads;
    for (int i = 0; i < NUM; i++)
    {
        ThreadData *td = new ThreadData();
        td->mutex_ptr = &mutex;
        threads.emplace_back(Ticket,*td);
        td->name = threads.back().GetName();
    }

    // 2. 启动线程
    for (auto &thread : threads)
    {
        thread.Start();
    }

    // 3. 等待线程
    for (auto &thread : threads)
    {
        thread.Join();
    }
    //销毁局部锁
    pthread_mutex_destroy(&mutex);
    return 0;
}




////全局锁
// int main()
// {
    
//     // 1. 构建线程对象
//     std::vector<Thread> threads;
//     for (int i = 0; i < NUM; i++)
//     {
//         threads.emplace_back(Ticket);
//     }

//     // 2. 启动线程
//     for (auto &thread : threads)
//     {
//         thread.Start();
//     }

//     // 3. 等待线程
//     for (auto &thread : threads)
//     {
//         thread.Join();
//     }
//     return 0;
// }